package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    /**
     * 发送短信验证码接口
     *
     * @param param
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String, String> param) {
        ErrorResult errorResult = null;
        //1.从页面传过来的手机号
        String phone = param.get("phone");

        //5.此方法可能会出现错误,所有用try...catch来包装一下
        try {
            //2.从业务层查询该手机发送的验证码是否失效
            //返回错误信息和错误码
            errorResult = this.smsService.sendCheckCode(phone);

            //3.如果返回的错误信息为空
            if (null == errorResult) {
                //4.通过响应体,返回响应的状态码
                //无参的ok()返回的是状态码,有参的ok()返回的是状态码+body()
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {

            //6.如果进入到catch中,说明调用业务层的方法,返回的是错误的信息,则说明发送短信验证码失败
            //利用日志打印错误信息,并打印手机号和错误信息
            log.error("发送短信验证码失败~ phone = " + phone, e);
        }

        //7.由于返回了错误信息,说明短信验证码发送失败,设置错误信息和状态码
        errorResult = ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败！").build();

        //8.向页面返回响应体的错误状态码和错误信息
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

}